package com.cet.programmercarl.algorithmperformancanalysis.二叉树.二叉树的遍历;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: algorithm
 * @description: 二叉树中序遍历
 * @author: 陈恩涛
 * @create: 2022-07-13 21:55
 **/
public class LC94 {

    public static void main(String[] args) {
        final TreeNode root = new TreeNode(1);
        final TreeNode treeNode2 = new TreeNode(2);
        root.right = treeNode2;
        treeNode2.left = new TreeNode(3);
        final List<Integer> list = inorderTraversal(root);
        list.forEach(System.out::println);

    }

    /**
     * 中序迭代遍历
     * @param root 根节点
     * @return 结果
     */
    public static List<Integer> inorderTraversal(TreeNode root) {
        final List<Integer> result = new ArrayList<>();
        final Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
//        stack.push(root);
//        while (!stack.isEmpty()) {
//            cur = stack.peek();
//            // 第二次访问
//            if(cur.left != null) {
//                stack.push(cur.left);
//            } else {
//                result.add(cur.val);
//                stack.pop();
//                if (cur.right != null) {
//                    stack.push(cur.right);
//                }
//            }
//
//        }

        // 巧妙化解了二次访问问题
        while (cur != null || !stack.isEmpty()){
            if (cur != null){
                stack.push(cur);
                cur = cur.left;
            }else{
                cur = stack.pop();
                result.add(cur.val);
                cur = cur.right;
            }
        }
        return result;
    }

    /**
     * 节点标记法
     * @param root 根节点
     * @return 结果
     */
    public static List<Integer> inorderTraversal2(TreeNode root) {
        final List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        final Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if (cur != null) {
                stack.pop();
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                // 二次访问出栈即可
                stack.push(cur);
                stack.push(null);
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            } else {
                // Null节点出栈
                stack.pop();
                cur = stack.pop();
                result.add(cur.val);
            }
        }
        return result;
    }

}
